package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.NursingProject;
import com.zzyl.entity.NursingProjectPlan;
import com.zzyl.entity.User;
import com.zzyl.exception.BusinessException;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.mapper.NursingProjectPlanMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.NursingProjectService;
import com.zzyl.vo.NursingProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 护理项目表 服务实现类
 * </p>
 *
 * @author 聂德祥
 * @since 2024-08-15
 */
@Service
public class NursingProjectServiceImpl extends ServiceImpl<NursingProjectMapper, NursingProject> implements NursingProjectService {
@Autowired
private UserMapper userMapper;
@Autowired
private NursingProjectPlanMapper nursingProjectPlanMapper;

    @Override
    public PageResponse<NursingProject> getNursingProjectAll(String name, Integer status, Integer page, Integer pageSize) {
        Page<NursingProject> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<NursingProject> nursingProjectVoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        nursingProjectVoLambdaQueryWrapper.like(StrUtil.isNotEmpty(name),NursingProject::getName,name).eq(status!=null,NursingProject::getStatus,status);
        Page<NursingProject> nursingProjectPage = getBaseMapper().selectPage(page1, nursingProjectVoLambdaQueryWrapper);
        nursingProjectPage.getRecords().stream().forEach(n->{
            User user = userMapper.selectById(n.getCreateBy());
            if(user!=null){
                n.setCreator(user.getNickName());
            }
        });

        return new  PageResponse(nursingProjectPage);
    }

    @Override
    public void removeByIdProject(Long id) {
        LambdaQueryWrapper<NursingProjectPlan> nursingProjectPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        nursingProjectPlanLambdaQueryWrapper.eq(NursingProjectPlan::getProjectId,id);
        Long count = nursingProjectPlanMapper.selectList(nursingProjectPlanLambdaQueryWrapper).stream().count();
        if(count>0){
            throw new BusinessException("该护理项目已有护理计划使用，不能删除");
        }
        removeById(id);

    }
}
